package websocketUtils

import (
	"context"
	"github.com/gorilla/websocket"
	"log"
	"net/url"
)

type WebsocketClient struct {
	Id     int32
	scheme string
	conn   *websocket.Conn //与 server的 conn
	reader WsMsg
}

func NewClient(scheme, serverAddr, path string) *WebsocketClient {
	u := url.URL{Scheme: "ws", Host: serverAddr, Path: path}
	var err error
	conn, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
	if err != nil {
		log.Fatal("dial:", err)
	}
	return &WebsocketClient{
		scheme: "ws",
		conn:   conn,
	}
}

type wsHandle = func(ctx context.Context, conn *websocket.Conn)

func (wc *WebsocketClient) Handler(handles ...wsHandle) {
	ctx, cancel := context.WithCancel(context.Background())
	//defer wc.connSet.Close()
	for _, handle := range handles {
		go handle(ctx, wc.conn)
	}
	cancel()
}

func (wc *WebsocketClient) Run(handle wsHandle) {
	ctx, cancel := context.WithCancel(context.Background())
	handle(ctx, wc.conn)
	cancel()
}
func (wc *WebsocketClient) SendMsg(messageType int, data iWebsocketClaims) {
	wc.reader.WriterClaims(messageType, data, wc.conn)
}
func (wc *WebsocketClient) ReadMsg(handle handle) {
	wc.reader.ReadMessageHandle(wc.conn, handle)
}
